package priv.pfz.basedao.mybatis.sqlprovider;

import org.apache.ibatis.builder.annotation.ProviderContext;
import priv.pfz.basedao.Utils;
import priv.pfz.basedao.info.FieldInfo;
import priv.pfz.basedao.info.DaoInfo;
import priv.pfz.basedao.mybatis.DaoInfoCache;
import priv.pfz.basedao.query.BaseQuery;
import priv.pfz.basedao.sharding.ShardingInfo;
import priv.pfz.basedao.sharding.ShardingManager;
import priv.pfz.basedao.sqlbuilder.SQL;

import java.util.Map;

/**
 * UPDATE table SET a=entity.a, b=entity.b WHERE query
 * @author yyjxp
 * 2024/1/28 23:55
 */
public class UpdateSqlProvider extends BaseSqlProvider {

    public String provideSql(Object entity, BaseQuery<?> query, ProviderContext context) {
        return innerProvideSql(entity, query, null, context);
    }

    public String provideShardingSql(Object entity, BaseQuery<?> query, ShardingInfo shardingInfo, ProviderContext context) {
        return innerProvideSql(entity, query, shardingInfo, context);
    }

    private String innerProvideSql(Object entity, BaseQuery<?> query, ShardingInfo shardingInfo, ProviderContext context) {
        Utils.checkNotNull(entity, "entity不能为空");
        Utils.checkNotNull(query, "query不能为空");
        query.overrideMyBatisPlaceholder("arg1");
        DaoInfo daoInfo = DaoInfoCache.getDaoInfo(context.getMapperType());
        ShardingManager shardingManager = new ShardingManager(daoInfo, shardingInfo);
        shardingManager.addShardingInfos(query);
        Map<String, Object> valueMap = getValueMap(daoInfo, entity);
        Utils.checkNotEmpty(valueMap, "entity字段不能全部为空");

        SQL sql = new SQL();
        sql.UPDATE(shardingManager.getShardingTable());
        for (FieldInfo fieldInfo : daoInfo.getFieldInfos()) {
            if (!valueMap.containsKey(fieldInfo.getFieldName())) {
                continue;
            }
            sql.SET(getFieldEquals("arg0", fieldInfo));
        }
        sql.WHERE(query.getConditionSql());
        if (daoInfo.isEnableLogicDelete()) {
            sql.WHERE(getLogicDeleteWhere(daoInfo));
        }
        String sqlStr = sql.toString();
        sqlStr += shardingManager.getThirdShardingStr();
        System.out.println(sqlStr);
        return sqlStr;
    }
}
